package cn.deepmax.spring.cloud.system.user.service.impl;

import cn.deepmax.spring.cloud.system.user.entity.User;
import cn.deepmax.spring.cloud.system.user.mapper.UserMapper;
import cn.deepmax.spring.cloud.system.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.Timestamp;
import java.util.Optional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public Optional<User> findUser(Long id) {

        User user = userMapper.findUser(id);
        if(user==null)
            return Optional.empty();
        else
            return Optional.of(user);
    }

    @Override
    public Boolean login(String name, String password) {

        User user = userMapper.findUserByNameAndPassword(name, password);
        return user!=null;
    }

    @Override
    public Boolean addUser(String name, String password) {
        if(!StringUtils.hasText(password))
            return false;
        User oldUser = userMapper.findByName(name);
        if(oldUser !=null)
            return false;
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        Timestamp now = new Timestamp(System.currentTimeMillis());
        user.setCreateTime(now);
        user.setUpdateTime(now);
        userMapper.save(user);
        return true;
    }
}
